package com.web.model;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.web.util.HtmlStringHandler;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.List;

/**
 * Created by reeves on 2015/7/4.
 * PageInfo类属于Model层，对应数据库表page_info
 */
/*
page_info表
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| pageId         | mediumint(9) | NO   | PRI |         | auto_increment |
| pageDate       | date         | YES  |     |         |                |
| pageContent    | longtext     | YES  |     |         |                |
| titleImage     | varchar(15)  | YES  |     |         |                |
| firstTitle     | varchar(64)  | YES  |     |         |                |
| typeId         | mediumint(4) | NO   |     |         |                |
| readNumber     | int(8)       | YES  |     |         |                |
| collectNumber  | int(8)       | YES  |     |         |                |
| transmitNumber | int(8)       | YES  |     |         |                |
| praNum         | mediumint(8) | YES  |     |         |                |
| criNum         | mediumint(8) | YES  |     |         |                |
| pageType       | tinyint(4)   | NO   |     |         |                |
| pageFrom       | varchar(40)  | NO   |     |         |                |
| recomPos       | tinyint(2)   | NO   |     |    -1   |                |
+----------------+--------------+------+-----+---------+----------------+
*/

/**
 * 说明：由于三级界面的信息没有单独的表或者视图对应，所以PageInfo-Model里面会有三级页面相关数据获取的信息
 */
public class PageInfo extends Model<PageInfo> {
    public static final PageInfo pageInfoDao = new PageInfo();
    /*创建Logger静态对象*/
    private static final Logger LOGGER = Logger.getLogger(PageInfo.class);


    /**
     * 将从page_edit取出的当天要推送的信息
     *
     * @param pageEditList
     * @return
     */
    public boolean addTodayInfo(List<PageEdit> pageEditList) {

        try {
            for (int i = 0; i < pageEditList.size(); i++) {
                PageEdit pageEdit = pageEditList.get(i);
                new PageInfo().set("pageDate", pageEdit.get("pageDate")).set("pageContent", pageEdit.get("pageContent")).set("titleImage", pageEdit.get("titleImage")).set("firstTitle", pageEdit.get("firstTitle")).set("secondTitle",pageEdit.get("secondTitle")).set("typeId", pageEdit.get("typeId")).set("pageType", pageEdit.get("pageType")).set("pageFrom", pageEdit.get("pageFrom")).set("pageEditId",pageEdit.getInt("id")).set("isTodayRecom",pageEdit.getInt("isTodayRecom")).set("editorId",pageEdit.get("editorId")).set("recomPos", pageEdit.getInt("recomPos")).set("sourceAddress",pageEdit.get("sourceAddress")).set("subjectOrderIndex",pageEdit.get("subjectOrderIndex")).save();
            }
        } catch (Exception exception) {
            LOGGER.error(exception);
            return false;
        }
        return true;
    }

    /**
     * 去掉现有推荐信息的标识（推荐界面中除Banner之外的所有信息）
     *
     * @return
     */
    public boolean updateRecomFlag(){
        int updateResult = Db.update("UPDATE page_info SET isTodayRecom=0 WHERE isTodayRecom=1");
        if(updateResult==0){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 把page_edit中 isTodayRecom为1的信息在page_info中isTodayRecom也设置成1
     *
     * @returns
     */
    public boolean setTodayRecomFlag(){
//        int updateResult = Db.update("UPDATE page_info,page_edit SET page_info.isTodayRecom=1 WHERE page_info.pageEditId=page_edit.id AND page_edit.isTodayRecom=1");
        int updateResult = Db.update("UPDATE page_info,page_edit SET page_info.isTodayRecom=1,page_info.recomPos=page_edit.recomPos,page_info.secondTitle = page_edit.secondTitle,page_info.subjectOrderIndex = page_edit.subjectOrderIndex WHERE page_info.pageEditId=page_edit.id AND page_edit.isTodayRecom=1");
        if(updateResult==0){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 判断文章是否已经在app中
     * @param pageId
     * @return
     */
    public boolean isInApp(int pageId) {
        List<PageInfo> pageInfoList = pageInfoDao.find("SELECT * FROM page_info WHERE pageEditId = ?", pageId);
        if(pageInfoList.size()==0){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 同步更新app里的文章
     * @param pageId
     * @param content
     * @return
     * @throws IOException
     */
    public boolean updateAppPage(int pageId,String content) throws IOException{
        content = HtmlStringHandler.formatHtml(content);
        int updateResult = Db.update("UPDATE page_info SET pageContent = ? WHERE pageEditId = ?", content, pageId);
        if (updateResult==0){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 添加一篇文章到app， 即提前让文章进入page_info
     * @param pageId
     * @return
     */
    public boolean addOneInfo (int pageId){
        PageEdit pageEdit = PageEdit.pageEditDao.findById(pageId);
        try {
            new PageInfo().set("pageDate", pageEdit.get("pageDate")).set("pageContent", pageEdit.get("pageContent")).set("titleImage", pageEdit.get("titleImage")).set("firstTitle", pageEdit.get("firstTitle")).set("secondTitle",pageEdit.get("secondTitle")).set("typeId", pageEdit.get("typeId")).set("pageType", pageEdit.get("pageType")).set("pageFrom", pageEdit.get("pageFrom")).set("pageEditId",pageEdit.getInt("id")).set("isTodayRecom",pageEdit.getInt("isTodayRecom")).set("editorId",pageEdit.get("editorId")).set("recomPos", pageEdit.getInt("recomPos")).set("sourceAddress",pageEdit.get("sourceAddress")).set("subjectOrderIndex",pageEdit.get("subjectOrderIndex")).save();
        }catch (Exception e){
            LOGGER.error("添加一篇新文章到app出错",e);
            return false;
        }

        //标志该文章已进入app
        try {
            Db.update("UPDATE page_edit SET isValid=0 WHERE Id = ?",pageId);
        }catch (Exception e){
            LOGGER.error("写标志出错!明天可能出现两遍该文章！注意！！！",e);
            return false;
        }
        return true;
    }

    public List<Record> getTuiInfo(String keyWord){
        return Db.find("SELECT imageSrc,firstTitle,secondType,pageId FROM tuisong WHERE firstTitle like ?",keyWord);
    }
}
